<?php
/**
 * Helper to create tag clouds
 * 
 * @category Abovo
 * 
 * @package Abovo_View
 * 
 * @author Antti Holvikari <anttih@gmail.com>
 * 
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */

/**
 * Helper to create tag clouds
 * 
 * @category Abovo
 * 
 * @package Abovo_View
 */
class Abovo_View_Helper_TagCloud extends Solar_View_Helper {
    
    /**
     * Config keys
     * 
     * Available keys are:
     * 
     * `boundary_lower`: (int) In per centage how big is 
     * the smallest font size
     * 
     * `boundary_upper`: (int) In per centage how big is 
     * the biggest font size
     * 
     * `style`: (string) CSS class name for the surrounding div
     * element
     * 
     * `attribs`: (array) Additional attributes to <a> -tags
     * 
     * @var array
     */
    protected $_Abovo_View_Helper_TagCloud = array(
        'boundary_lower' => 100,
        'boundary_upper' => 300,
        'style'          => 'tagcloud',
        'attribs' => array(
            'style' => '',
        ),
    );
    
    /**
     * Creates a div with <a></a> links with correct font sizes
     *
     * @param $tags array Tag name => tag count assoc array
     * 
     * @param $base string String suitable for action view helper
     * to create a href to one tag.
     * 
     * @param $attribs array Additional attribs to add to <a> tags
     * 
     * @return string XHTML
     */
    public function tagCloud($tags, $base, $attribs = array())
    {
        $total = 0;
        $tag_count = count($tags);
        
        foreach ($tags as $tag => $count) {
            $total += $tags[$tag];
        }
        
        $attribs = array_merge($this->_config['attribs'], $attribs);
        $attribs = $this->_view->attribs($attribs);
        
        // list of hrefs
        $hrefs = array();
        
        foreach ($tags as $tag => $count) {
            
            // how much does this count take from the whole scale
            $size = ($count / $total) 
                  * ($this->_config['boundary_upper'] 
                  - $this->_config['boundary_lower']);
            
            // replace tag name placeholder with tag name
            $href = sprintf($base, $tag);
            
            // round to one decimal
            $size = round($this->_config['boundary_lower'] + $size, 1);
            $attribs['style'] = "font-size: $size%";
            
            $hrefs[] = $this->_view->action($href, $tag, $attribs);
        }
        
        $xhtml  = '<div class="' . $this->_config['style'] .'">' . "\n";
        $xhtml .= implode("\n", $hrefs) . "\n";
        $xhtml .= '</div>';
        
        return $xhtml;
    }
}
